 using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Xml.Serialization;
using System.Linq;
using System.Text;
using Sio.Mdm.Entities;
using Sio.Mdm.Server;
using Sio.Mdm.BF.Ldap;
using Sio.Mdm.Connector;
using Sio.Mdm.BF.Idm;
using Sio.Mdm.Client;
using Sio.Mdm.Types.Database;
using Sio.Mdm.Types;

namespace Sio.Mdm.BL.Ldap
{
    [Service(Name = "LdapService", DefaultInterface = typeof(ILdapService))]
    public class LdapService : ILdapService
    {
        const string _idmStevilka = "IdmStevilka"; 
        ldapMigrationSchemaConfig _ldapMigrationSchemaConfig = null;
        ldapMigrationSchemaFields _ldapMigrationSchemaFields = null;
        List<int> _selected = null;

        Connector.ConnectorMono _ldapConnector;
        DataProvider _dataProvider = null;
        LdapLogHelper _logHelper = null;
        ldapMigrationSchema _migrationSchema;                

        enum TipStoritve { 
            LDAP_Skupina = 1,
            AD_Skupina = 2
        }

        enum curentActionType
        { 
            Insert,
            Update,
            Delete
        }

        #region Properties
        #region schemaPath
        private static string schemaPath
        {
            get
            {
                string path = ConfigurationManager.AppSettings["ldapMigrationSchemaPath"];

                if (String.IsNullOrEmpty(path) || path == "default")
                {
                    path = AppDomain.CurrentDomain.BaseDirectory.ToString();
                }
                else 
                {
                    if (path.Contains(":")) return path;

                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                }

                return path;
            }
        }
        private DataProvider DataProvider
        {
            get {
                return _dataProvider;
            }
        }

        private ldapMigrationSchemaConfig LdapMigrationSchemaConfig
        {
            get {
                if (_ldapMigrationSchemaConfig == null){
                    _ldapMigrationSchemaConfig = GetXMLSchemaSection<ldapMigrationSchemaConfig>(_migrationSchema);    
                }
                return _ldapMigrationSchemaConfig;
            }
        }

        private ldapMigrationSchemaFields LdapMigrationSchemaFields
        {
            get
            {
                if (_ldapMigrationSchemaFields == null)
                {
                    _ldapMigrationSchemaFields = GetXMLSchemaSection<ldapMigrationSchemaFields>(_migrationSchema);
                }
                return _ldapMigrationSchemaFields;
            }
        }

        #endregion
        #endregion 

        public LdapService()
        {

        }

        #region Methods
        
        #region Public
        public Result Test(Session session) 
        {
            //GetLdapADGroups(100, "CN=Users,DC=Sarma,DC=local", session);                            

            return null;
        }

        public Result TestUceciSync(int letoId, int razredId, int razred, Session session)
        {
            //LoadTest();
            //return null;
            //SaveLog();
            //LoadTest();
            return null;

            Result result = initialize();
            if (result != null) return result;

            //EntityCollection<Ucec> uceci = LoadUceci(letoId, razredId, razred, session);

            //List<ldapObject> dataList = PrepareLdapObject(_migrationSchema, uceci);

            //SyncToLdap(dataList);

            return null;
        }

        public Result TestConnection(int streznikId, Session session)
        {
            try
            {
                _dataProvider = new DataProvider(session);

                // Prepare connection data for StreznikID
                Result result = DataProvider.LoadStreznik(streznikId);
                if (result != null) return result;

                // Connect to Streznik based on sreznik config
                result = Connect();
                if (result != null) return result;

                _ldapConnector.Exists("x1x2x3x4", Sio.Mdm.Connector.Connector.eLdapSearchField.Username, Sio.Mdm.Connector.Connector.eLdapSearchScope.oneLevel);
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }

            return null;
        }

        #region Synchronization
        public Result AutoStartSync()
        {
            return null;
        }
        
        public Result UserRequestSync(int razredId, Session session)
        {
            return UserRequestSync(razredId, new List<int>(), session);
        }

        public Result UserRequestSync(int razredId, List<int> selected, Session session)
        {
            _dataProvider = new DataProvider(session);
            _logHelper = new LdapLogHelper(LdapLogHelper.eSyncType.UserRequestData, session);

            Result result = DataProvider.PrepareDataUserRequestRazred(razredId);
            if (result != null) return result;
            _selected = selected;

            // (1) Ni pravil po katerih bi lahko izvajali sinhronizacijo
            if (DataProvider.PravilaCount == 0)
            {
                return null;
            }

            result = Synchronize();

            _logHelper.Save(result);
            return result;
        }

        public Result UserRequestSyncPravilo(int praviloId, Session session)
        {
            _dataProvider = new DataProvider(session);
            _logHelper = new LdapLogHelper(LdapLogHelper.eSyncType.UserRequestPravilo, session);

            Result result = DataProvider.PrepareDataUserRequestPravilo(praviloId);

            // (1) Ni pravil po katerih bi lahko izvajali sinhronizacijo
            if (DataProvider.PravilaCount == 0)
            {
                return null;
            }

            result = Synchronize();

            _logHelper.Save(result);
            return result;
        }

        public Result UserRequestDelete(int razredId, Session session)
        {
            return Test(session);
            //return UserRequestDelete(razredId, new List<int>(), session);
        }
        public Result UserRequestDelete(int razredId, List<int> selected, Session session)
        {
            _dataProvider = new DataProvider(session);
            _logHelper = new LdapLogHelper(LdapLogHelper.eSyncType.UserRequestData, session);

            Result result = DataProvider.PrepareDataUserRequestRazred(razredId);
            if (result != null) return result;
            _selected = selected;

            if (DataProvider.PravilaCount == 0)
            {
                return null;
            }

            result = Synchronize(true);

            _logHelper.Save(result);
            return result;
        }

        public Result UserRequestDeletePravilo(int praviloId, Session session)
        {
            _dataProvider = new DataProvider(session);
            _logHelper = new LdapLogHelper(LdapLogHelper.eSyncType.UserRequestData, session);

            Result result = DataProvider.PrepareDataUserRequestPravilo(praviloId);

            // (1) Ni pravil po katerih bi lahko izvajali sinhronizacijo
            if (DataProvider.PravilaCount == 0)
            {
                return null;
            }

            result = Synchronize(true);

            _logHelper.Save(result);
            return null;
        }
        #endregion

        #region Config
        public Result GetLdapADGroups(int streznikId, string baseDN, out List<ldapObject> groups, Session session)
        {            
            groups = null;

            try
            {
                _dataProvider = new DataProvider(session);

                // Prepare connection data for StreznikID
                Result result = DataProvider.LoadStreznik(streznikId);
                if (result != null) return result;

                // Connect to Streznik based on sreznik config
                result = Connect();
                if (result != null) return result;

                groups = _ldapConnector.LoadGroups(baseDN);
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }
            
            return null;
                        
        }

        public Result SaveLdapADGroup(int streznikId, string baseDN, string groupDN, Session session)
        {
            Result result;
            try
            {
                if (_dataProvider!=null && DataProvider.ldapStreznik!=null) {
                    if (DataProvider.ldapStreznik.LdapStreznikID!=streznikId) {
                        _dataProvider = null;   
                    } 
                }

                if (_dataProvider==null) {
                    _dataProvider = new DataProvider(session);

                    // Prepare connection data for StreznikID
                    result = DataProvider.LoadStreznik(streznikId);
                    if (result != null) return result;
                }

                // Connect to Streznik based on sreznik config
                result = Connect();
                if (result != null) return result;

                string groupName = "[AD]";
                if (DataProvider.ldapStreznik.Tip == (int)Connector.Connector.eLdapDirectoryType.OpenLdap) groupName = "[LDAP]";
                groupName = String.Format("{0} {1}", groupName, Connector.Connector.GetBaseCN(groupDN));                

                result = SaveLdapADGroup(DataProvider.ldapStreznik.LdapStreznikID, DataProvider.ldapStreznik.OrgarnizacijaID, groupName, groupName, DataProvider.ldapStreznik.Tip, groupDN, session);
                if (result != null) return result;

                return null;
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }

            return null;
        }
        #endregion

        #endregion

        #region Private

        #region initialize
        private Result initialize()
        {
            Result result = null; ;

            result = Connect();
            if (result != null) return result;

            result = LoadXMLSchema();
            if (result != null) return result;

            return null;
        }
        #endregion

        #region Connect
        /// <summary>
        /// Safe connect based on DataProvider. 
        /// </summary>
        /// <returns></returns>
        private Result Connect()
        {
            try
            {
                // (1) If already connected to the right server, we can use current connection...
                if (_ldapConnector != null && _ldapConnector.isConnected) {
                    if (_ldapConnector.Server == DataProvider.ldapStreznik.Naslov)
                        return null;
                }

                Sio.Mdm.Connector.Connector.eLdapDirectoryType dirType = Sio.Mdm.Connector.Connector.eLdapDirectoryType.ActiveDirectory;
                if (DataProvider.ldapStreznik.Tip == (int)Sio.Mdm.Connector.Connector.eLdapDirectoryType.OpenLdap) {
                    dirType = Sio.Mdm.Connector.Connector.eLdapDirectoryType.OpenLdap;
                }                

                // (2) Connect to the server that is provided by DataProvider
                if (_ldapConnector != null) _ldapConnector = null;
                _ldapConnector = new Sio.Mdm.Connector.ConnectorMono(dirType, DataProvider.ldapStreznik.RootDN);
                                                   
                _ldapConnector.Connect(DataProvider.ldapStreznik.Naslov, DataProvider.ldapStreznik.Uporabnik, DataProvider.ldapStreznik.Geslo, DataProvider.ldapStreznik.SslPovezava);                

            }
            catch (Exception ex)
            {
                return new Result(ex);
            }

            return null;
        }
        #endregion

        #region LoadXMLSchema
        private Result LoadXMLSchema()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ldapMigrationSchema));

                string path = Path.Combine(schemaPath, DataProvider.ldapPredloga.Datoteka);

                TextReader reader = new StreamReader(path);
                _migrationSchema = (ldapMigrationSchema)serializer.Deserialize(reader);
                _ldapMigrationSchemaConfig = null;
                _ldapMigrationSchemaFields = null;
                reader.Close();
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }

            return null;
        }
        #endregion

        #region GetXMLSchemaSection
        private T GetXMLSchemaSection<T>(ldapMigrationSchema schema)
        {
            T result = default(T);
            for (int i = 0; i < schema.Items.Length; i++)
            {
                string h = typeof(T).ToString();
                string t = schema.Items[i].ToString();

                if (schema.Items[i].ToString() == typeof(T).ToString())
                { 
                    result = (T)schema.Items[i];
                    break;
                }
            }
            return result;
        }
        #endregion

        #region GetLdapSchema*
        private String[] GetLdapSchemaObjectClass()
        {            
            ldapMigrationSchemaConfigDefaultsObjectClassClass[] classes = LdapMigrationSchemaConfig.defaults[0].objectClass;

            String[] objectClass = new String[classes.Length];

            for (int i = 0; i < classes.Length; i++)
            {
                objectClass[i] = classes[i].name;
            }

            return objectClass;
        }

        private ldapMigrationSchemaFieldsField GetLdapSchemaField(string fieldName)
        {
            for (int i = 0; i < LdapMigrationSchemaFields.field.Length; i++)
            {
                ldapMigrationSchemaFieldsField field = LdapMigrationSchemaFields.field[i];
                if (field.destinationField == fieldName)
                {
                    return field;
                }
            }
            return null;
        }
        #endregion

        #region PrepareLdapObjects
        private ldapObject PrepareLdapObject(IEntity entity, curentActionType action)
        {
            ldapObject data = new ldapObject();                                                  
            data.DN = DataProvider.ldapPravilo.BaseDN;
            data.objectClass = GetLdapSchemaObjectClass();
            
            for (int i = 0; i < LdapMigrationSchemaFields.field.Length; i++)
            {
                if (CheckEvent(LdapMigrationSchemaFields.field[i].fieldEvent, action))
                {
                    ldapMigrationSchemaFieldsField field = LdapMigrationSchemaFields.field[i];

                    object formatedFieldValue = FormatFieldForLdap(field, entity);

                    data.Add(field.destinationField, formatedFieldValue);
                }
            }
            return data;
        }
        #endregion

        #region FormatFieldForLdap
        private object FormatFieldForLdap(ldapMigrationSchemaFieldsField field, IEntity xEntity)
        {
            //TODO: We must check here if fieldName exists before reading...

            object _fieldValue = "";
            string destinationFormat="{0}";

            // if destinationFormat is specified, use it.
            if (!String.IsNullOrEmpty(field.destinationFormat)) 
            {
                destinationFormat = field.destinationFormat;
            }

            // STEP 1 - get formated value
            if (string.IsNullOrEmpty(field.sourcedb))
            {
                _fieldValue = destinationFormat; 
            }
            else if (field.sourcedb.Contains(","))
            {
                string[] fields = field.sourcedb.Split(',');
                object[] fieldValues = new object[fields.Length];
                for (int i=0; i < fields.Length; i++)
                {
                    fieldValues[i] = xEntity.GetField(fields[i]).ToString();
                }
                _fieldValue = String.Format(destinationFormat, fieldValues);                
            }
            else
            {
                _fieldValue = String.Format(destinationFormat, xEntity.GetField(field.sourcedb).ToString());
            }

            // STEP 2 - encoding
            if (!string.IsNullOrEmpty(field.destinationEncoding))
            {
                if (field.destinationEncoding.ToUpper().Contains("NOSPACES")) {
                    _fieldValue = _fieldValue.ToString().Replace(" ", "");
                }
                if (field.destinationEncoding.ToUpper().Contains("ONLYASCII")) {
                    _fieldValue = ToAsciiText(_fieldValue.ToString());                    
                }
                                
                if (field.destinationEncoding.ToUpper().Contains("UNICODE")) {
                    _fieldValue = EncodeToUnicode(Convert.ToString(_fieldValue));      
                }
                if (field.destinationEncoding.ToUpper().Contains("HASH"))
                {
                    _fieldValue = EncodeHash(Convert.ToString(_fieldValue));
                }        
            }

            // STEP 3 - max len
            if (!string.IsNullOrEmpty(field.maxLenght))
            {
                int maxLenght = 0;
                Int32.TryParse(field.maxLenght, out maxLenght);
                if (maxLenght > 0)
                {
                    if (_fieldValue.ToString().Length > maxLenght)
                    {
                        _fieldValue = _fieldValue.ToString().Substring(0, maxLenght);
                    }
                }
            }
            

            return _fieldValue;
        }
        #endregion

        #region CheckEvent
        private bool CheckEvent(string fieldEvent, curentActionType action)
        {
            if (fieldEvent == null) return true;                        // if not specified, ALL is the default
            if (fieldEvent.ToUpper().Contains("ALL")) return true;

            switch (action)
            { 
                case curentActionType.Insert:
                    if (fieldEvent.ToUpper().Contains("INSERT")) return true;
                    break;
                case curentActionType.Update:
                    if (fieldEvent.ToUpper().Contains("UPDATE")) return true;
                    break;
            }

            return false;
        }
        #endregion

        #region SyncToLdap
        private Result SyncToLdap(EntityCollection entities)
        {            
            ldapMigrationSchemaFieldsField idField = GetLdapSchemaField(LdapMigrationSchemaConfig.uniqueField);
            Result result = null;

            try
            {
                foreach (IEntity xEntity in entities)
                {
                    if (SkipThisEntity(xEntity)) continue;

                    string ldapUniqueFieldValue = (String)FormatFieldForLdap(idField, xEntity);
                    int IdmStevilka = xEntity.GetField<int>("IdmStevilka");

                    if (!_ldapConnector.Exists(ldapUniqueFieldValue,
                        Sio.Mdm.Connector.Connector.eLdapSearchField.Username,      // TODO: dinamično izberi polje ?
                        Sio.Mdm.Connector.Connector.eLdapSearchScope.oneLevel,
                        DataProvider.ldapPravilo.BaseDN))
                    {
                        // INSERT
                        ldapObject ldapObj = PrepareLdapObject(xEntity, curentActionType.Insert);   // prepare ldapObject
                        string uniqueCN = FindUniqueCN(ldapObj.CN);

                        if (uniqueCN != ldapObj.CN) ldapObj.CN = uniqueCN;

                        _ldapConnector.Add(ldapObj);
                        if (_logHelper != null) _logHelper.AddINS();

                        // Add to / remove from groups
                        List<string> skupine = DataProvider.GetClanSkupine(IdmStevilka);
                        result = AddRemoveGroups(ldapObj.DN, new List<string>(), skupine);
                        if (result != null) return result;                        
                    }
                    else 
                    { 
                        // UPDATE
                        ldapObject ldapObj = PrepareLdapObject(xEntity, curentActionType.Update);   // prepare ldapObject
                        ldapObject ldapObjCurrent = _ldapConnector.Load(_ldapConnector.LastDN);     // load the one found by Exists...

                        ldapObj = _ldapConnector.GetDiff(ldapObj, ldapObjCurrent);

                        if (!ldapObjCurrent.CN.Contains(ldapObj.CN))                    // Check if CN shoud be renamed...
                        {
                            // TODO: find unique...
                            _ldapConnector.RenameCN(ldapObjCurrent.DN, ldapObj.CN);     // Some special case to rename CN
                        }

                        // TODO: Check if password was changed...

                        if (ldapObj.Count() > 0) {
                            _ldapConnector.Update(ldapObj);
                            if (_logHelper != null) _logHelper.AddUPD();
                        }

                        // Add to / remove from groups
                        List<string> skupine = DataProvider.GetClanSkupine(IdmStevilka);
                        result = AddRemoveGroups(ldapObj.DN, ldapObjCurrent.MemberOf, skupine);
                        if (result != null) return result; 
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }
        }
        #endregion

        #region DeleteFromLdap
        private Result DeleteFromLdap(EntityCollection entities)
        {
            ldapMigrationSchemaFieldsField idField = GetLdapSchemaField(LdapMigrationSchemaConfig.uniqueField);

            try
            {
                foreach (IEntity xEntity in entities)
                {
                    if (SkipThisEntity(xEntity)) continue;

                    string ldapUniqueFieldValue = (String)FormatFieldForLdap(idField, xEntity);

                    if (_ldapConnector.Exists(ldapUniqueFieldValue,
                        Sio.Mdm.Connector.Connector.eLdapSearchField.Username,      // TODO: dinamično izberi polje ?
                        Sio.Mdm.Connector.Connector.eLdapSearchScope.oneLevel,
                        DataProvider.ldapPravilo.BaseDN))
                    {
                        // DELETE
                        _ldapConnector.Delete(_ldapConnector.LastDN);

                        if (_logHelper != null) _logHelper.AddDEL();
                    }
                    else
                    {
                        // NOT FOUND
                        
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }
        }
        #endregion

        #region SkipThisEntity
        private bool SkipThisEntity(IEntity xEntity)
        {
            // Skip if nothing specified
            if (_selected==null || _selected.Count==0)
            {
                return false;
            }

            // Check if this entity is selected
            int id = Convert.ToInt32(xEntity.GetField(_idmStevilka));
            if (_selected.Contains(id))
            {
                return false;
            }

            return true;
        }
        #endregion

        #region FindUniqueCN
        private string FindUniqueCN(string CN)
        {            
            bool existsCN = _ldapConnector.Exists(CN, Sio.Mdm.Connector.Connector.eLdapSearchField.CN, Sio.Mdm.Connector.Connector.eLdapSearchScope.oneLevel, DataProvider.ldapPravilo.BaseDN);
            if (existsCN == false) return CN;

            string newCN="";
            int i = 2;

            while (existsCN)            
            {
                newCN=String.Format("{0} ({1})", CN, i);
                existsCN = _ldapConnector.Exists(newCN, Sio.Mdm.Connector.Connector.eLdapSearchField.CN, Sio.Mdm.Connector.Connector.eLdapSearchScope.oneLevel, DataProvider.ldapPravilo.BaseDN);
                i++;
            }
            return newCN;
        }
        #endregion

        #region LoadUceci
        private EntityCollection<Ucec> LoadUceci(int letoId, int razredId, int razred, Session session)
          {
              
              return null;
          }
        #endregion

        #region Encode*
        private byte[] EncodeToUnicode(string data)
        {
            string formated = String.Format("\"{0}\"",data);
            return (Encoding.Unicode.GetBytes(formated));
        }

        private string EncodeHash(string data)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] input = Encoding.UTF8.GetBytes(data);
            byte[] result = md5.ComputeHash(input);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }
            return sb.ToString();
        }
        #endregion

        #region Synchronize*
        private Result Synchronize()
        {
            return Synchronize(false);
        }

        private Result Synchronize(bool deleteAll)
        {
            Result result = DataProvider.PravilaNext();
            if (result != null) return result;            

            // (1) PRAVILA 
            while (DataProvider.PravilaIsLoaded)
            {
                result = DataProvider.DataNext();
                if (result != null) return result;

                // (2) DATA
                while (DataProvider.DataIsLoaded)
                {
                    // (3) CONNECT IF NECCESSARY
                    result = initialize();
                    if (result != null) return result;

                    EntityCollection entities = DataProvider.Data;
                    //List<ldapObject> ldapObjectList = PrepareLdapObjects(_migrationSchema, entities);
                    if (_logHelper != null)
                    {
                        _logHelper.SetPravilo(DataProvider.ldapPravilo.LdapPraviloID, DataProvider.ldapStreznik.OrgarnizacijaID);
                        _logHelper.AddReport(String.Format("Naloženo št. entitet: {0} po predlogi: {1}", entities.Count, DataProvider.ldapPredloga.Ime));                        
                    }

                    if (deleteAll)
                        result = DeleteFromLdap(entities);
                    else
                        result = SyncToLdap(entities);

                    if (result != null) return result;

                    result = DataProvider.DataNext();
                    if (result != null) return result;
                }

                result = DataProvider.PravilaNext();
                if (result != null) return result;                
            }
            
            return null;
        }
        #endregion

        private Result AddRemoveGroups(string userDN, List<string> currentGroups, List<string> newGroups)
        {
            if (newGroups == null) return null;
            string forError = "";

            try
            {
                // (1) Check for ADD
                foreach (string group in newGroups)
                {
                    if (!currentGroups.Contains(group))
                    {
                        forError = String.Format("NAPAKA pri dodeljevanju v skupino: {0} za {1}", group, userDN);
                        _ldapConnector.AddToGroup(group, userDN);
                        if (_logHelper != null) _logHelper.AddGINS();
                    }
                }

                // (2) Check for DELETE
                foreach (string group in currentGroups)
                {
                    if (!newGroups.Contains(group))
                    {
                        forError = String.Format("NAPAKA pri odstranjevanju iz skupine: {0} za {1}", group, userDN);
                        _ldapConnector.RemoveFromGroup(group, userDN);
                        if (_logHelper != null) _logHelper.AddGDEL();
                    }
                }
            }
            catch (Exception ex)
            {
                if (_logHelper != null) _logHelper.AddError(forError);
                return new Result(ex);    
            }

            return null;
        }

        private void LoadTest()
        {
            //var slService = ServiceFactory.GetService<ILdapPredlogeService>();
            //EntityCollection<LdapPredloga> _ldapPredloga = null;

            //slService.Select(ref _ldapPredloga, t => t.LdapPredlogaID != null, null);

            //int z = _ldapPredloga.Count();
            //ldapPredloge[

            LdapPredloga predloga = EntityFactory.CreateInstance<LdapPredloga>();
            predloga.LdapPredlogaID = 5;
            predloga.OrgarnizacijaID = -2;
            predloga.Ime = "T";
            predloga.Opis = "VV";
            predloga.DatumVnosa = DateTime.Now;
            predloga.Datoteka = "rr";

            var slService2 = ServiceFactory.GetService<ILdapPredlogeService>();
            slService2.Create(predloga, null);
        }

        

        private string ToAsciiText(string text)
        {
            text = text.Replace("š", "s").Replace("Š", "S");
            text = text.Replace("č", "c").Replace("Č", "C");
            text = text.Replace("ž", "z").Replace("Ž", "Z");
            return text;
        }

        #region SaveLdapADGroup
        private Result SaveLdapADGroup(int streznikID, int orgarnizacijaID, string skupinaName, string storitevName, int tipStoritveID, string storitevParam, Session session)
        {
            try
            {
                SkupinaStoritevRazsirjeno skupinaStoritev = EntityFactory.CreateInstance<SkupinaStoritevRazsirjeno>();

                //UTF8Encoding encoding = new UTF8Encoding();
                //skupinaStoritev.Config = encoding.GetBytes(config);
                skupinaStoritev.OrgarnizacijaID = orgarnizacijaID;
                skupinaStoritev.SkupinaNaziv = skupinaName;
                skupinaStoritev.StoritevNaziv = storitevName;
                skupinaStoritev.TipStoritveID = tipStoritveID;
                skupinaStoritev.StoritevKljuc = streznikID;
                skupinaStoritev.StoritevParam = storitevParam;

                var slService = ServiceFactory.GetService<ISkupineStoritveRazsirjenoService>();
                slService.Create(skupinaStoritev, session);
            }
            catch (Exception ex)
            {
                return new Result(ex);
            }

            return null;
        }
        #endregion

        #endregion
        #endregion

    }
}
